package org.bluedream.core.config.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.bluedream.comm.utils.EmptyUtil;
import org.bluedream.core.config.exception.LicenseNullException;
import org.bluedream.core.config.exception.OrgNotPermitException;
import org.bluedream.core.config.exception.OrgNullPointException;
import org.bluedream.core.module.login.service.LoginService;
import org.bluedream.core.module.sys.entity.User;
import org.bluedream.core.module.sys.service.SysLicenseService;
import org.bluedream.core.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private LoginService loginService;

    @Autowired
    private SysLicenseService sysLicenseService;


    @Override
    public boolean isPermitted(PrincipalCollection principals, String permission) {
        String loginCode = principals.getPrimaryPrincipal().toString();
        return UserUtil.isSystem(loginCode) ||super.isPermitted(principals, permission);
    }

    @Override
    public boolean hasRole(PrincipalCollection principal, String roleIdentifier) {
        String loginCode = principal.getPrimaryPrincipal().toString();
        return UserUtil.isSystem(loginCode)||super.hasRole(principal, roleIdentifier);
    }

    /**
     * 授权信息
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        try {
            // 获取登录用户
            String loginCode = principalCollection.getPrimaryPrincipal().toString();
            User user = loginService.getLoginUser(loginCode);
            // 添加角色 、 权限 至shiro 权限管理器
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//            List<Role> roleList = loginService.getRoleList(user);
//            List<Menu> permissions = loginService.getMenuPermissions(user);

            authorizationInfo.addRoles(loginService.getRoleIds(user));

            authorizationInfo.addStringPermissions(loginService.getMenuPermissions2String(user));
            return authorizationInfo;
        }catch (Exception e1){
            e1.printStackTrace();
        }
        return null;
    }

    /**
     * 用户登录时的 身份认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        CustomUsernamePasswordToken token = (CustomUsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String orgCode = token.getOrgCode();

        String loginCode = authenticationToken.getPrincipal().toString();
        if (EmptyUtil.isEmpty(orgCode)){
            throw new OrgNullPointException("登录组织不能为空");
        }

        //checkLoginValidityByOrg方法：验证登录用户是否拥有登录该组织的权限
        User loginUser = loginService.checkLoginValidityByOrg(loginCode , orgCode);
        if (EmptyUtil.isEmpty(loginUser)){
            throw new OrgNotPermitException("登录组织没有授权或账号信息错误");
        }

        boolean flag = sysLicenseService.check();
        if (!flag){
            throw new LicenseNullException("系统未经授权，请联系系统管理员！");
        }

        return new SimpleAuthenticationInfo(loginCode, loginUser.getPassword(), ByteSource.Util.bytes(loginCode) , this.getClass().getName());
    }

}
